﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>待检任务管理</title>
    <link rel="stylesheet" href="../../scripts/layui-v2.5.6/layui/css/layui.css">
    <script src="../../scripts/jquery-3.4.1.min.js"></script>
    <script src="../../scripts/layui-v2.5.6/layui/layui.js"></script>
</head>
<body>
<style>
    .container {
        padding: 15px;
        background-color: #f2f2f2;
    }
    .content {
        background-color: #fff;
        padding: 15px;
        border-radius: 2px;
    }
    .search-form {
        margin-bottom: 15px;
        padding: 15px;
        background-color: #f8f8f8;
        border-radius: 2px;
    }
    .auto-generate-switch {
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        user-select: none;
        white-space: nowrap;
    }
    .switch-text {
        font-size: 12px;
        color: #666;
    }
    .switch-toggle {
        position: relative;
        width: 40px;
        height: 20px;
        background-color: #ccc;
        border-radius: 10px;
        transition: background-color 0.3s ease;
    }
    .switch-toggle.active {
        background-color: #5fb878;
    }
    .switch-circle {
        position: absolute;
        top: 2px;
        left: 2px;
        width: 16px;
        height: 16px;
        background-color: white;
        border-radius: 50%;
        transition: transform 0.3s ease;
        box-shadow: 0 1px 3px rgba(0,0,0,0.3);
    }
    .switch-toggle.active .switch-circle {
        transform: translateX(20px);
    }
</style>

<div class="container">
    <div class="content">
        <!-- 搜索栏 -->
        <div class="search-form">
            <div class="layui-form" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">单据编码</label>
                        <div class="layui-input-inline">
                            <input type="text" name="searchFormCode" placeholder="请输入单据编码" autocomplete="off" class="layui-input" id="searchFormCode">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">物资名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="searchMaterialName" placeholder="请输入物资名称" autocomplete="off" class="layui-input" id="searchMaterialName">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">检测类型</label>
                        <div class="layui-input-inline">
                            <select name="searchTestingItems" id="searchTestingItems">
                                <option value="">请选择检测类型</option>
                                <option value="过程检验">过程检验</option>
                                <option value="进货检验">进货检验</option>
                                <option value="出货检验">出货检验</option>
                                <option value="首件检验">首件检验</option>
                                <option value="巡检">巡检</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn" id="searchBtn"><i class="layui-icon layui-icon-search"></i> 搜索</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="resetBtn"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据表格 -->
        <table id="pendingtasksTable" lay-filter="pendingtasksTable"></table>
    </div>
</div>

<!-- 表格操作列模板 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="process">过程检验</a>
</script>

<script>
layui.use(['form', 'table', 'layer', 'laydate'], function(){
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var $ = layui.$;

    // 初始化表格
    table.render({
        elem: '#pendingtasksTable',
        url: '/Pendingtasks/GetPendingtasksPageList', // 使用新的分页接口
        method: 'get',
        request: {
            pageName: 'page',
            limitName: 'limit'
        },
        where: {},
        page: {
            curr: 1,
            limit: 10,
            limits: [5, 10, 15, 20],
            layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
        },
        toolbar: true,
        defaultToolbar: ['filter', 'exports', 'print'],
        parseData: function(res) {
            console.log('后端返回的数据:', res);
            // 后端已经返回了layui需要的格式
            return {
                "code": res.code,
                "msg": res.msg,
                "count": res.count,
                "data": res.data
            };
        },
        cols: [[
            {type: 'checkbox'},
            {field: 'id', title: 'ID', width: 80, hide: true},
            {field: 'formCode', title: '单据编码', width: 160},
            {field: 'testingItems', title: '检测项型', width: 120},
            {field: 'materialCode', title: '物资编码', width: 140},
            {field: 'materialName', title: '物资名称', width: 200},
            {field: 'pendingNum', title: '待检数量', width: 120, align: 'center'},
            {field: 'position', title: '位置', width: 120},
            {title: '操作', toolbar: '#tableBar', width: 120, fixed: 'right'}
        ]],
        response: {
            statusCode: 0
        },
        text: {
            none: '暂无相关数据'
        },
        loading: true,
        done: function(res, curr, count) {
            console.log('表格渲染完成，当前页：', curr, '总数：', count);
        }
    });

    // 重置按钮点击事件
    $('#resetBtn').on('click', function(){
        $('#searchFormCode').val('');
        $('#searchMaterialName').val('');
        $('#searchTestingItems').val('');
        form.render('select'); // 重新渲染select
        
        var loading = layer.load(1);
        table.reload('pendingtasksTable', {
            where: {},
            page: {
                curr: 1
            },
            done: function() {
                layer.close(loading);
                layer.msg('已重置搜索条件');
            }
        });
    });

    // 搜索框回车事件
    $('#searchFormCode, #searchMaterialName').on('keydown', function(e){
        if(e.keyCode === 13) {
            $('#searchBtn').trigger('click');
        }
    });

    // 搜索按钮点击事件
    $('#searchBtn').on('click', function(){
        var formCode = $('#searchFormCode').val().trim();
        var materialName = $('#searchMaterialName').val().trim();
        var testingItems = $('#searchTestingItems').val();
        
        var whereCondition = {};
        if(formCode) {
            whereCondition.formCode = formCode;
        }
        if(materialName) {
            whereCondition.materialName = materialName;
        }
        if(testingItems) {
            whereCondition.testingItems = testingItems;
        }
        
        console.log('搜索条件:', whereCondition);
        
        var loading = layer.load(1, {
            content: '正在搜索...'
        });
        
        table.reload('pendingtasksTable', {
            where: whereCondition,
            page: {
                curr: 1
            },
            done: function(res, curr, count) {
                layer.close(loading);
                var searchText = '';
                var conditions = [];
                if(formCode) conditions.push(`单据编码"${formCode}"`);
                if(materialName) conditions.push(`物资名称"${materialName}"`);
                if(testingItems) conditions.push(`检测类型"${testingItems}"`);
                searchText = conditions.join('和');
                
                if(count > 0) {
                    layer.msg(`搜索到 ${count} 条符合条件的记录`);
                } else {
                    layer.msg(`未找到符合${searchText}的记录`, {icon: 2});
                }
            }
        });
    });

    // 表格工具条事件
    table.on('tool(pendingtasksTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'process'){
            openProcessForm(data);
        }
    });

    // 打开过程检验表单
    function openProcessForm(data) {
        console.log('传入的数据:', data); // 调试用
        
        // 获取检验类型的选中状态
        var getTestingTypeOptions = function(currentValue) {
            var options = [
                { value: '', text: '请选择检验类型' },
                { value: '过程检验', text: '过程检验' },
                { value: '进货检验', text: '进货检验' },
                { value: '出货检验', text: '出货检验' },
                { value: '首件检验', text: '首件检验' },
                { value: '巡检', text: '巡检' }
            ];
            return options.map(opt => 
                `<option value="${opt.value}" ${opt.value === currentValue ? 'selected' : ''}>${opt.text}</option>`
            ).join('');
        };

        var content = `
            <div style="padding: 20px;">
                <form class="layui-form" lay-filter="processForm" id="processForm">
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">检验单编号 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="processCode" placeholder="请输入检验单编号" autocomplete="off" class="layui-input" lay-verify="required" value="${data.formCode || ''}">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">检验类型 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <select name="processType" lay-verify="required">
                                        ${getTestingTypeOptions(data.testingItems || '')}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">工单编号 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <div style="display: flex; align-items: center; gap: 10px;">
                                        <input type="text" name="orderCode" id="orderCode" placeholder="请输入工单编号" autocomplete="off" class="layui-input" lay-verify="required" style="flex: 1;">
                                        <div class="auto-generate-switch" onclick="toggleAutoGenerate()">
                                            <span class="switch-text">自动生成</span>
                                            <div class="switch-toggle" id="autoGenerateToggle">
                                                <div class="switch-circle"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">产品物料编码 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="productCode" placeholder="请输入产品物料编码" autocomplete="off" class="layui-input" lay-verify="required" value="${data.materialCode || ''}">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">产品物料名称 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="productName" placeholder="请输入产品物料名称" autocomplete="off" class="layui-input" lay-verify="required" value="${data.materialName || ''}">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">规格型号</label>
                                <div class="layui-input-block">
                                    <input type="text" name="specifications" placeholder="请输入规格型号" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">单位</label>
                                <div class="layui-input-block">
                                    <input type="text" name="unitt" placeholder="请输入单位" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">检测数量 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input type="number" name="testingNum" placeholder="请输入检测数量" autocomplete="off" class="layui-input" lay-verify="required|number" value="${data.pendingNum || ''}">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">检测结果</label>
                                <div class="layui-input-block">
                                    <select name="testingResult">
                                        <option value="">请选择检测结果</option>
                                        <option value="合格">合格</option>
                                        <option value="不合格">不合格</option>
                                        <option value="待定">待定</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">检测日期 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="testingDate" id="testingDate" placeholder="请选择检测日期" autocomplete="off" class="layui-input" lay-verify="required">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">检测人员 <span style="color: red;">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="testingPerson" placeholder="请输入检测人员" autocomplete="off" class="layui-input" lay-verify="required">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">单据状态</label>
                                <div class="layui-input-block">
                                    <select name="state">
                                        <option value="0" selected>草稿</option>
                                        <option value="1">已提交</option>
                                        <option value="2">已审核</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        `;

        layer.open({
            type: 1,
            title: '过程检验',
            area: ['900px', '600px'],
            content: content,
            btn: ['保存', '取消'],
            yes: function(index, layero) {
                // 提交表单
                form.on('submit(processForm)', function(formData) {
                    return false; // 阻止表单跳转
                });
                
                // 获取表单数据
                var formData = form.val('processForm');
                console.log('表单数据:', formData);
                
                if (!formData.processCode) {
                    layer.msg('请输入检验单编号', {icon: 2});
                    return;
                }
                if (!formData.processType) {
                    layer.msg('请选择检验类型', {icon: 2});
                    return;
                }
                if (!formData.orderCode) {
                    layer.msg('请输入工单编号', {icon: 2});
                    return;
                }
                if (!formData.productCode) {
                    layer.msg('请输入产品物料编码', {icon: 2});
                    return;
                }
                if (!formData.productName) {
                    layer.msg('请输入产品物料名称', {icon: 2});
                    return;
                }
                if (!formData.testingNum || formData.testingNum <= 0) {
                    layer.msg('请输入有效的检测数量', {icon: 2});
                    return;
                }
                if (!formData.testingDate) {
                    layer.msg('请选择检测日期', {icon: 2});
                    return;
                }
                if (!formData.testingPerson) {
                    layer.msg('请输入检测人员', {icon: 2});
                    return;
                }

                // 转换数据格式
                var processData = {
                    processCode: formData.processCode,
                    processType: formData.processType,
                    orderCode: formData.orderCode,
                    productCode: formData.productCode,
                    productName: formData.productName,
                    specifications: formData.specifications || '',
                    unitt: formData.unitt || '',
                    testingNum: parseInt(formData.testingNum),
                    testingResult: formData.testingResult || '',
                    testingDate: formData.testingDate,
                    testingPerson: formData.testingPerson,
                    state: parseInt(formData.state) || 0
                };

                var loading = layer.load(1);
                
                // 提交数据
                $.ajax({
                    url: '/Pendingtasks/AddProcess',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(processData),
                    success: function(response) {
                        layer.close(loading);
                        if (response.success) {
                            layer.msg(response.message, {icon: 1});
                            layer.close(index);
                            // 刷新表格
                            table.reload('pendingtasksTable');
                        } else {
                            layer.msg(response.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.close(loading);
                        layer.msg('请求失败，请重试', {icon: 2});
                    }
                });
            },
                        success: function(layero, index) {
                // 渲染表单
                form.render();
                
                // 初始化日期选择器
                laydate.render({
                    elem: '#testingDate',
                    type: 'date',
                    value: new Date(),
                    format: 'yyyy-MM-dd'
                });

                // 自动生成状态
                var autoGenerateEnabled = false;

                // 生成工单编号的函数
                function generateOrderCode() {
                    var now = new Date();
                    var year = now.getFullYear();
                    var month = String(now.getMonth() + 1).padStart(2, '0');
                    var day = String(now.getDate()).padStart(2, '0');
                    var hours = String(now.getHours()).padStart(2, '0');
                    var minutes = String(now.getMinutes()).padStart(2, '0');
                    var seconds = String(now.getSeconds()).padStart(2, '0');
                    var milliseconds = String(now.getMilliseconds()).padStart(3, '0');
                    
                    // 生成格式：WO + 年月日时分秒毫秒，例如：WO20240625143025001
                    var orderCode = 'WO' + year + month + day + hours + minutes + seconds + milliseconds;
                    
                    // 设置到输入框
                    document.getElementById('orderCode').value = orderCode;
                    
                    return orderCode;
                }

                // 切换自动生成开关的函数
                window.toggleAutoGenerate = function() {
                    autoGenerateEnabled = !autoGenerateEnabled;
                    var toggle = document.getElementById('autoGenerateToggle');
                    var orderInput = document.getElementById('orderCode');
                    
                    if (autoGenerateEnabled) {
                        toggle.classList.add('active');
                        // 立即生成一个工单编号
                        var orderCode = generateOrderCode();
                        // 禁用输入框
                        orderInput.disabled = true;
                        orderInput.style.backgroundColor = '#f5f5f5';
                        layer.msg('已开启自动生成，工单编号：' + orderCode, {icon: 1, time: 2000});
                    } else {
                        toggle.classList.remove('active');
                        // 启用输入框
                        orderInput.disabled = false;
                        orderInput.style.backgroundColor = '';
                        // 清空输入框
                        orderInput.value = '';
                        layer.msg('已关闭自动生成，可手动输入工单编号', {icon: 0, time: 2000});
                    }
                };
            }
        });
    }
});
</script>
</body>
</html>
